package com.yay.danceline.io;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;


/**
 * Get Started!
 * @author yakovlev.yuriy@gmail.com
 * @author Dmitry Makeev
 */
public class DataHandler {
	private static final String TAG = "DataHandler";
	private SQLiteDatabase db;
	private Context context;
	private final static String SEP = ";";
	
	public DataHandler(Context context, SQLiteDatabase db) {
		 this.context = context;
		 this.db = db;
	}
	
    public void insertTracks() {
    	BufferedReader reader = null;
        InputStreamReader in = null;
        SQLiteStatement stmt = null;
        try{
        	in = new InputStreamReader(context.getAssets().open("tracks.csv"));
            reader = new BufferedReader(in, 1024);
        	db.beginTransaction();
    		String[] data = null;
    		String text = null;
    		stmt = db.compileStatement("insert into tracks (idp, artist, name, url) values (?,?,?,?)");
    		while(((text = reader.readLine()) != null)) {
                if(!(text.length() > 1024)) {
                	data = text.split(SEP);
                	stmt.bindLong(1, Integer.valueOf(data[0]));
                	stmt.bindString(2, data[1]);
                	stmt.bindString(3, data[2]);
                	stmt.bindString(4, data[3]);
                	stmt.execute();
                }
            }
            db.setTransactionSuccessful();
        } catch(Exception e) {
        	Log.e(TAG, e.toString());
        } finally {
        	try {
        		db.endTransaction();
        		stmt.close();
        		if(reader != null) {
                    reader.close();
                }
                if(in != null) {
                	in.close();
                }
            } catch(Exception e) {
            	Log.e(TAG, e.toString());
            }
        }
    }

}
